package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.common.utils.appkit.ConfigKit;
import com.firefightingiot.firefightingiot.common.utils.appkit.FirefightingiotKit;
import com.firefightingiot.firefightingiot.model.DeviceAlarmLog;
import com.firefightingiot.firefightingiot.model.DeviceBusiness;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.MyLogger;
import com.firefightingiot.firefightingiot.web.mapper.DeviceAlarmLogMapper;
import com.firefightingiot.firefightingiot.web.mapper.DeviceBusinessMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

//import org.bytedeco.javacpp.opencv_core;
//import org.bytedeco.javacv.*;

@Service
@Slf4j
public class FireService extends BaseService {

    @Resource
    public MyLogger logger;

    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    private DeviceAlarmLogMapper deviceAlarmLogMapper;

    //@Async
    public RespEntity restFile(JSONObject jsonParam) throws InterruptedException, ParseException {
        //Thread.sleep(1000);
        logger.info("------------------------------------restFile:"+jsonParam.toString() +"-----------------------------------------------------");
        logger.info("------------------------------------restFile:"+"-----------------------------------------------------");
        //设备号
        String DevID = jsonParam.getStr("number");
        //报警唯一号
        String AlarmID = jsonParam.getStr("fireId");
        //处理时间
        String DoTime = jsonParam.getStr("handletime");
        //处理人
        String DoUser = jsonParam.getStr("handlePerson");
        //处理内容
        String DoResult = jsonParam.getStr("handleRemark");
        //报警时间
        String alarmTime = jsonParam.getStr("alarmTime");
        //设备类型
        String DevType = "";
        //设备详情
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusinessList == null || deviceBusinessList.isEmpty()) return RespEntity.fail("设备编号错误");
        DeviceBusiness deviceBusiness = deviceBusinessList.get(0);
        //rest请求单位详情接口，获取单位信息
        JSONObject businessJsonParamN = new JSONObject();
        businessJsonParamN.put("id", deviceBusiness.getBusinessId());
        com.alibaba.fastjson.JSONObject businessDetail = makeDatas(businessJsonParamN, "businessJava", "getBusinessDetailNoToken", "business", "GET");
        if (StrUtil.isNotBlank(businessDetail.getString("methodErrorFlag")))
            return RespEntity.fail(businessDetail.getString("msg"));
        if (deviceBusiness.getDeviceClassify().equals("1")) {
            DevType = "01";
        }
        if (deviceBusiness.getDeviceClassify().equals("2")) {
            //水压
            if (deviceBusiness.getWaterattr().equals("1")) {
                DevType = "02";
            }
            //水位
            if (deviceBusiness.getWaterattr().equals("2")) {
                DevType = "03";
            }
        }
        if (deviceBusiness.getDeviceClassify().equals("6")) {
            DevType = "05";
        }
        if (deviceBusiness.getDeviceClassify().equals("3")) {
            DevType = "06";
        }
        //解析之后的数据
        JSONObject jsonParamN = new JSONObject();
        //消防支队token
        String xftoken = "";
        String orgIds = deviceBusiness.getAllId();
        String strs[] = orgIds.split(",");
        if (deviceBusiness.getOrgId().equals("e349f82a-c7a7-4e67-a1ff-ae0aca8940f3")){
            //圣斌仁晟
            jsonParamN.put("DevID", "AHH" + deviceBusiness.getNumber());
            xftoken =FirefightingiotKit.getStr("sbrsfirefightingToken","jointFire");
        } else {
            xftoken =FirefightingiotKit.getStr("zhyfirefightingToken","jointFire");
            jsonParamN.put("DevID","ABB"+DevID);
        }
        jsonParamN.put("AlarmID", AlarmID);
        jsonParamN.put("DoTime", DoTime);
        jsonParamN.put("DoUser", DoUser);
        jsonParamN.put("DoResult", "报警信息于"+alarmTime+"通过微信的方式发送至单位管理人"+businessDetail.getString("safeResponPersonName")+",接收号码为"+businessDetail.getString("safeResponPersonPhone"));
        jsonParamN.put("DevType", DevType);
        logger.info("------------------------------------fireFile:"+jsonParamN.toString()+"-----------------------------------------------------");
        String fireFlag = ConfigKit.getStr("fireFlag", "config");
        if(fireFlag.equals("1")){
            try {
                RespEntity respEntity = fireFightingIotJsonRest(jsonParamN,"fireBrigade","alarmHandle","jointFire","POST",xftoken);
                JSONObject jsonObject = new JSONObject(respEntity.getData());
                if (jsonObject.getBool("Success")){
                    //消防支队处置成功更新状态
                    DeviceAlarmLog deviceAlarmLog = new DeviceAlarmLog();
                    deviceAlarmLog.setFireState(1);
                    deviceAlarmLogMapper.update(deviceAlarmLog,new QueryWrapper<DeviceAlarmLog>().eq("fire_id",AlarmID));
                }
            }catch (Exception e){
                System.out.println("消防支队请求超时:"+e);
            }

        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 报警恢复
     * @Date Created in 14:21 2022/3/11
     * @Param [jsonParam]
     */
    //@Async
    public RespEntity restRecoverFile(JSONObject jsonParam) throws InterruptedException {
        logger.info("------------------------------------restFile:"+jsonParam.toString() +"-----------------------------------------------------");
        logger.info("------------------------------------restFile:"+"-----------------------------------------------------");
        //设备类型
        String DevType = "";
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusinessList == null || deviceBusinessList.isEmpty()) return RespEntity.fail("设备编号错误");
        Map<String,String> maps = new HashMap<>();
        DeviceBusiness deviceBusiness = deviceBusinessList.get(0);
        if (deviceBusiness.getDeviceClassify().equals("1")) {
            DevType = "01";
            maps = getVoltageValue();
        }else if (deviceBusiness.getDeviceClassify().equals("2")) {
            //水压
            if (deviceBusiness.getWaterattr().equals("1")) {
                DevType = "02";
                Map<String,String> map = new HashMap<>();
                map.put("3003","压力正常");
                maps = map;
            }
            //水位
            if (deviceBusiness.getWaterattr().equals("2")) {
                DevType = "03";
                Map<String,String> map = new HashMap<>();
                map.put("3103","水位正常");
                maps = map;
            }
        }else if (deviceBusiness.getDeviceClassify().equals("3")) {
            DevType = "06";
            Map<String,String> map = new HashMap<>();
            map.put("7004","恢复正常");
            maps = map;
        }else {
            return RespEntity.success();
        }
        for (Map.Entry<String, String> entry: maps.entrySet()){
            //解析之后的数据
            JSONObject jsonParamN = new JSONObject();
            //消防支队token
            String xftoken = "";
            if (deviceBusiness.getOrgId().equals("e349f82a-c7a7-4e67-a1ff-ae0aca8940f3")){
                //圣斌仁晟
                jsonParamN.put("DevID", "AHH" + deviceBusiness.getNumber());
                xftoken =FirefightingiotKit.getStr("sbrsfirefightingToken","jointFire");
            } else {
                xftoken =FirefightingiotKit.getStr("zhyfirefightingToken","jointFire");
                jsonParamN.put("DevID","ABB"+deviceBusiness.getNumber());
            }
            jsonParamN.put("AlarmID", UUID.randomUUID().toString());
            jsonParamN.put("AlarmTime", jsonParam.getStr("handletime"));
            jsonParamN.put("AlarmType", entry.getKey());
            jsonParamN.put("Data", entry.getValue());
            jsonParamN.put("DevType", DevType);
            logger.info("------------------------------------fireFile:"+jsonParamN.toString()+"-----------------------------------------------------");
            String fireFlag = ConfigKit.getStr("fireFlag", "config");
            if(fireFlag.equals("1")){
                try {
                    fireFightingIotJsonRest(jsonParamN,"fireBrigade","alarmData","jointFire","POST",xftoken);
                }catch (Exception e){
                    System.out.println("消防支队请求超时:"+e);
                }

            }
        }
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 解析时间格式：年月日时分
     * @Date Created in 11:00 2022/3/14
     */

    public static String getTime(String time) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm");
        Date date = formatter.parse(time);
        String str = formatter.format(date);
        return str;
    }
    public static Map<String,String> getVoltageValue(){
        Map<String,String> map = new HashMap<>();
        map.put("4001","漏电恢复正常");
        map.put("4002","电压A恢复正常");
        map.put("4003","电压B恢复正常");
        map.put("4004","电压C恢复正常");
        map.put("4005","温度A恢复正常");
        map.put("4006","温度B恢复正常");
        map.put("4007","温度C恢复正常");
        map.put("4008","温度N恢复正常");
        map.put("4009","电流A恢复正常");
        map.put("4010","电流B恢复正常");
        map.put("4011","电流C恢复正常");
        return map;
    }

    public static void main(String[] args) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        System.out.println(format.format(date));
        format = new SimpleDateFormat("yyyy");
        System.out.println(format.format(date));
        format = new SimpleDateFormat("MM");
        System.out.println(format.format(date));
    }
}
